﻿using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Missbot.Common;
using Missbot.Core.Cache;
using Missbot.Core.Common;
using Missbot.Core.Scheduler;
using Missbot.Model.MsgCmds.Notes;

namespace Missbot.AIModule.Schedulers.InstanceStats
{
    [UsedImplicitly]
    public class StatsMonitorScheduler : IScheduler
    {
        protected override List<ScheduleMeta> ModelList { get; set; }

        public override string Owner => "iceai";

        protected override void ScheduleDo(SchedulerTimer timer)
        {
            var lastStatus = StatusMonitorRecDA.GetNewest() ?? new StatusMonitorRec();
            var rtStatus = Requestor.GetInstanceStatus();

            var dic = new Dictionary<string, string>
            {
                {
                    "发现的实例数",
                    $"{CommonUtil.NumberFomat(rtStatus.Instances)} ({CommonUtil.NumberFormatWithSymbol(rtStatus.Instances - lastStatus.Instances)})"
                },
                {
                    "嘟文总数",
                    $"{CommonUtil.NumberFomat(rtStatus.NotesCount)} ({CommonUtil.NumberFormatWithSymbol(rtStatus.NotesCount - lastStatus.NotesCount)})"
                },
                {
                    "本地嘟文总数",
                    $"{CommonUtil.NumberFomat(rtStatus.OriginalNotesCount)} ({CommonUtil.NumberFormatWithSymbol(rtStatus.OriginalNotesCount - lastStatus.OriginalNotesCount)})"
                },
                {
                    "用户总数",
                    $"{CommonUtil.NumberFomat(rtStatus.UsersCount)} ({CommonUtil.NumberFormatWithSymbol(rtStatus.UsersCount - lastStatus.UsersCount)})"
                },
                {
                    "本地用户总数",
                    $"{CommonUtil.NumberFomat(rtStatus.OriginalUsersCount)} ({CommonUtil.NumberFormatWithSymbol(rtStatus.OriginalUsersCount - lastStatus.OriginalUsersCount)})"
                }
            };
            MsgSender.PushMsg(new CreateNoteCmd { Text = $"#实例状态报告 \n{string.Join("\n", dic.Select(kv => $"{kv.Key}: {kv.Value}"))}" });

            var rec = new StatusMonitorRec
            {
                Instances = rtStatus.Instances,
                NotesCount = rtStatus.NotesCount,
                OriginalNotesCount = rtStatus.OriginalNotesCount,
                UsersCount = rtStatus.UsersCount,
                OriginalUsersCount = rtStatus.OriginalUsersCount
            };
            rec.Insert();
        }

        public override void Work()
        {
            var lastStatus = StatusMonitorRecDA.GetNewest();
            var isAlreadySend = lastStatus?.DateStr == DateTime.Now.ToString("yyyyMMdd");
            ModelList = new List<ScheduleMeta> { new() { IsImmediately = !isAlreadySend, Span = new FixHourSpan { FixHour = 0 } } };

            base.Work();
        }
    }
}